package com.wakey.rtcs.web.controller;

import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.wakey.rtcs.miniui.PageManager;
import com.wakey.rtcs.web.model.Attach;
import com.wakey.rtcs.web.model.DocInfo;
import com.wakey.rtcs.web.service.DocService;

@Controller
@RequestMapping("/doc")
public class DocController {
	@Autowired
	private DocService docService;

	@RequestMapping(value = "saveDocInfo")
	@ResponseBody
	public boolean saveDocInfo(String name,String projectName,Integer level,String type){
		String code = UUID.randomUUID().toString().replace("-", "").substring(1,10); 
		DocInfo info = new DocInfo();
		info.setCode(code);info.setName(name);info.setProjectName(projectName);
		info.setLevel(level);info.setCreateTime(new Date());
		int num = docService.saveDocInfo(info);	
		return num>0 ? true:false;
	}
	
	@RequestMapping(value = "deleteDocInfo")
	@ResponseBody
	public boolean deleteDocInfo(String id){
		String[] ids = id.split(",");
		if(ids.length == 0) return false;
		int num = docService.deleteDocInfo(ids);	
		return num>0 ? true:false;
	}
	
	@RequestMapping(value = "/docInfoList")
	@ResponseBody
	private PageManager<DocInfo> queryAllDocInfo(DocInfo docInfo, HttpServletRequest request, PageManager<DocInfo> page) {
		List<DocInfo> list = docService.queryAllDocInfo(docInfo);
		page.setData(list);
		return page;
	}
	
	@RequestMapping({"upload"})
	public void upload(HttpServletRequest request, HttpServletResponse response) throws Exception {
		String method = request.getMethod();
		Map<String, Object> result = new HashMap<String, Object> ();
		List<Attach> attachList = new ArrayList<Attach>();
		response.setContentType("text/plain");
		if ("POST".equals(method.toUpperCase())) {
	        //String uuid = UUID.randomUUID().toString().replace("-", ""); 
	        Attach attach = this.docService.uploadFile(request);
			attachList.add(attach);
		}

		result.put("files", attachList);
		result.put("filePath", "/upload");
		ObjectMapper mapper = new ObjectMapper();
		response.setCharacterEncoding("UTF-8");
		response.getWriter().write(mapper.writeValueAsString(result));
	}

	@RequestMapping({"deleteUploadFile"})
	@ResponseBody
	public boolean deleteUploadFile(HttpServletRequest request,String fileName) throws Exception {
		return docService.deleteUploadFile(request,fileName);
	}

}
